<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区" prop="communityId">
        <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            filterable
        >
          <el-option v-for="c in community" :label="c.name || c.communityId" :value="c.communityId"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="楼宇名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入楼宇名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼宇编号" prop="buildingNo">
        <el-input
            v-model="queryParams.buildingNo"
            placeholder="请输入楼宇编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总楼层数" prop="totalFloors">
        <el-input
            v-model="queryParams.totalFloors"
            placeholder="请输入总楼层数"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单元数" prop="unitCount">
        <el-input
            v-model="queryParams.unitCount"
            placeholder="请输入单元数"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑结构" prop="buildingStructure">
        <el-input
            v-model="queryParams.buildingStructure"
            placeholder="请输入建筑结构"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼宇用途" prop="buildingPurpose">
        <el-input
            v-model="queryParams.buildingPurpose"
            placeholder="请输入楼宇用途"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建成日期" prop="builtDate">
        <el-date-picker clearable
                        v-model="queryParams.builtDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择建成日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="验收日期" prop="acceptanceDate">
        <el-date-picker clearable
                        v-model="queryParams.acceptanceDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择验收日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="建筑面积" prop="buildingArea">
        <el-input
            v-model="queryParams.buildingArea"
            placeholder="请输入建筑面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用面积" prop="usableArea">
        <el-input
            v-model="queryParams.usableArea"
            placeholder="请输入使用面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否有储物间" prop="hasStorage">
        <el-input
            v-model="queryParams.hasStorage"
            placeholder="请输入是否有储物间"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间编号规则" prop="roomNumberRule">
        <el-input
            v-model="queryParams.roomNumberRule"
            placeholder="请输入房间编号规则"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['comsys:building:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['comsys:building:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['comsys:building:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['comsys:building:export']"
        >导出
        </el-button>
      </el-col>
      <!-- 在现有按钮区域添加导入按钮 -->
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['comsys:building:import']"
        >导入
        </el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="buildingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="楼宇ID" align="center" prop="buildingId"/>
      <el-table-column label="社区" align="center" prop="communityId">
        <template #default="scope">
          <span>{{ getCommunityName(scope.row.communityId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="楼宇名称" align="center" prop="name"/>
      <el-table-column label="楼宇编号" align="center" prop="buildingNo"/>
      <el-table-column label="总楼层数" align="center" prop="totalFloors"/>
      <el-table-column label="单元数" align="center" prop="unitCount"/>
      <el-table-column label="建筑结构" align="center" prop="buildingStructure"/>
      <el-table-column label="楼宇类型" align="center" prop="buildingType"/>
      <el-table-column label="楼宇用途" align="center" prop="buildingPurpose"/>
      <el-table-column label="建成日期" align="center" prop="builtDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.builtDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="验收日期" align="center" prop="acceptanceDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.acceptanceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="建筑面积" align="center" prop="buildingArea">
        <template #default="scope">
          <span>{{ scope.row.buildingArea ? scope.row.buildingArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用面积" align="center" prop="usableArea">
        <template #default="scope">
          <span>{{ scope.row.buildingArea ? scope.row.buildingArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否有储物间" align="center" prop="hasStorage"/>
      <el-table-column label="房间编号规则" align="center" prop="roomNumberRule"/>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="楼宇图片" align="center" prop="images">
        <template #default="scope">
          <div v-if="scope.row.images" class="table-image-container">
            <el-image
                :src="scope.row.images"
                :preview-src-list="[scope.row.images]"
                class="table-preview-item"
                fit="cover"
                lazy
            />
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['comsys:building:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['comsys:building:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改楼宇管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="buildingRef" :model="form" :rules="rules" label-width="80px">
        <!-- 社区下拉框 -->
        <el-form-item label="社区" prop="communityId">
          <el-select
              v-model="form.communityId"
              placeholder="请选择社区"
              clearable
              filterable
          >
            <el-option v-for="c in community" :label="c.name || c.communityId" :value="c.communityId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼宇名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入楼宇名称"/>
        </el-form-item>
        <el-form-item label="楼宇编号" prop="buildingNo">
          <el-input v-model="form.buildingNo" placeholder="请输入楼宇编号"/>
        </el-form-item>
        <el-form-item label="总楼层数" prop="totalFloors">
          <el-input v-model="form.totalFloors" placeholder="请输入总楼层数"/>
        </el-form-item>
        <el-form-item label="单元数" prop="unitCount">
          <el-input v-model="form.unitCount" placeholder="请输入单元数"/>
        </el-form-item>
        <el-form-item label="建筑结构" prop="buildingStructure">
          <el-input v-model="form.buildingStructure" placeholder="请输入建筑结构"/>
        </el-form-item>
        <el-form-item label="楼宇用途" prop="buildingPurpose">
          <el-input v-model="form.buildingPurpose" placeholder="请输入楼宇用途"/>
        </el-form-item>
        <el-form-item label="建成日期" prop="builtDate">
          <el-date-picker clearable
                          v-model="form.builtDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择建成日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="验收日期" prop="acceptanceDate">
          <el-date-picker clearable
                          v-model="form.acceptanceDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择验收日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="建筑面积" prop="buildingArea">
          <el-input v-model="form.buildingArea" placeholder="请输入建筑面积"/>
        </el-form-item>
        <el-form-item label="使用面积" prop="usableArea">
          <el-input v-model="form.usableArea" placeholder="请输入使用面积"/>
        </el-form-item>
        <el-form-item label="是否有储物间" prop="hasStorage">
          <el-input v-model="form.hasStorage" placeholder="请输入是否有储物间"/>
        </el-form-item>
        <el-form-item label="房间编号规则" prop="roomNumberRule">
          <el-input v-model="form.roomNumberRule" placeholder="请输入房间编号规则"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择或输入状态" clearable filterable allow-create>
            <el-option label="有效" value="有效"></el-option>
            <el-option label="空置" value="空置"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片(JSON数组)" prop="images">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/upload/img"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
          >
            <img v-if="form.images" :src="form.images" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <div style="text-align: center; padding: 20px 0;">
        <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :on-change="handleFileChange"
            :file-list="fileList"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" class="link-type" @click="handleTemplate">下载模板</el-link>
            </div>
          </template>
        </el-upload>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Building">
import {listBuilding, getBuilding, delBuilding, addBuilding, updateBuilding} from "@/api/comsys/building"
import {ElMessage} from "element-plus";
import {getToken} from "@/utils/auth.js";
import {importBuilding} from "@/api/comsys/mange.js";
import request from "@/utils/request.js";

const {proxy} = getCurrentInstance()
const router = useRouter()

const buildingList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    name: null,
    buildingNo: null,
    totalFloors: null,
    unitCount: null,
    buildingStructure: null,
    buildingType: null,
    buildingPurpose: null,
    builtDate: null,
    acceptanceDate: null,
    buildingArea: null,
    usableArea: null,
    hasStorage: null,
    roomNumberRule: null,
    description: null,
    images: null,
    status: null
  },
  rules: {}
})

const {queryParams, form, rules} = toRefs(data)

/** 查询楼宇管理列表 */
function getList() {
  loading.value = true
  listBuilding(queryParams.value).then(response => {
    buildingList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    buildingId: null,
    communityId: null,
    name: null,
    buildingNo: null,
    totalFloors: null,
    unitCount: null,
    buildingStructure: null,
    buildingType: null,
    buildingPurpose: null,
    builtDate: null,
    acceptanceDate: null,
    buildingArea: null,
    usableArea: null,
    hasStorage: null,
    roomNumberRule: null,
    description: null,
    images: null,
    createTime: null,
    updateTime: null,
    status: null
  }
  proxy.resetForm("buildingRef")
}


const headers = ref({Authorization: "Bearer " + getToken()})

// 图片上传
const handleAvatarSuccess = (
    response
) => {
  ElMessage.success("上传成功")
  form.value.images = response.msg
  // console.log(response)
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.buildingId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加楼宇管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _buildingId = row.buildingId || ids.value
  getBuilding(_buildingId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改楼宇管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["buildingRef"].validate(valid => {
    if (valid) {
      if (form.value.buildingId != null) {
        updateBuilding(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBuilding(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _buildingIds = row.buildingId || ids.value
  proxy.$modal.confirm('是否确认删除楼宇管理编号为"' + _buildingIds + '"的数据项？').then(function () {
    return delBuilding(_buildingIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comsys/building/export', {
    ...queryParams.value
  }, `building_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false
});

const fileList = ref([]);
const uploadRef = ref(null);

// 导入按钮操作
function handleImport() {
  router.push({ path: '/comsys/building/import' })
}

// 文件上传相关函数
function handleExceed() {
  proxy.$modal.msgError("只能上传一个文件");
}

function handleFileChange(file, fileList) {
  this.fileList = fileList;
}

// 下载模板
function handleTemplate() {
  proxy.download("comsys/building/importTemplate", {}, `building_template.xlsx`);
}

// 提交上传文件
function submitFileForm() {
  if (fileList.value.length === 0) {
    proxy.$modal.msgError("请选择上传文件");
    return;
  }

  upload.isUploading = true;

  // 创建 FormData 对象
  const formData = new FormData();
  formData.append("file", fileList.value[0].raw);

  // 调用导入 API
  importBuilding(formData)
      .then(response => {
        upload.open = false;
        proxy.$modal.msgSuccess(response.msg);
        getList();
      })
      .catch(err => {
        console.error(err);
        proxy.$modal.msgError("导入失败");
      })
      .finally(() => {
        upload.isUploading = false;
      });
}

//查询社区id
const community = ref([]);
const initCommunity = () =>{
  request({
    url: `/communityVo/getCommunityVoNameById`,
    method: 'get'
  }).then((response) => {
    community.value = response.data;
  })
}

initCommunity();
getList()
// 显示社区名称而非ID
const getCommunityName = (id) => {
  const list = Array.isArray(community.value) ? community.value : []
  const item = list.find(c => String(c.communityId) === String(id))
  return item ? (item.name ?? item.communityId) : id
}
</script>


<style scoped>
.avatar-uploader, .avatar-uploader.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover { border-color: var(--el-color-primary); }
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
/* 保留现有图片样式并统一尺寸 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}
</style>

<style scoped>
/* 作用于整个表单 */
:deep(.el-form) {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: dense; /* 支持跨列元素 */
}

/* 让 textarea、图片上传等宽元素占满两列 */
:deep(.el-form-item--large),
:deep(.el-form-item[label='详细地址']),
:deep(.el-form-item[label='社区描述']),
:deep(.el-form-item[label='图片(JSON数组)']),
:deep(.el-form-item[label='经纬度']) {
  grid-column: span 2;
}

/* 可选：调整 label 宽度适应新布局 */
:deep(.el-form-item__label) {
  width: 108px !important;
}
</style>